package com.xuanwei.core.entity.bo;

import com.google.common.collect.Lists;
import com.xuanwei.dao.entity.XwManagement;
import com.xuanwei.dao.entity.XwManagementRole;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author jiangyong
 * @Description TODO 后端用户
 * @Date 2019/4/17 17:24
 **/
public class UserDetail implements UserDetails {

    private XwManagement management;

    private XwManagementRole role;

    public UserDetail(XwManagement management, XwManagementRole role) {
        this.management = management;
        this.role = role;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> permissions = Lists.newArrayList();
        String value = role.getValue();
        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(value);
        permissions.add(simpleGrantedAuthority);
        List<SimpleGrantedAuthority> collect = role.getPermissions().stream()
                .filter(permission -> permission.getValue() != null)
                .map(permission -> new SimpleGrantedAuthority(permission.getValue()))
                .collect(Collectors.toList());
        permissions.addAll(collect);
        return permissions;
    }

    public XwManagement getManagement() {
        return management;
    }

    public XwManagementRole getRole() {
        return role;
    }

    @Override
    public String getPassword() {
        return management.getPassword();
    }

    @Override
    public String getUsername() {
        return management.getUsername();
    }

    /**
     * 账户是否过期,过期无法验证
     *
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 指定用户是否被锁定或者解锁,锁定的用户无法进行身份验证
     *
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
     *
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
